package com.sk.sourcecircle.activity.home.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.adapter.CityListAdapter;
import com.sk.sourcecircle.adapter.HotCityAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.OnItemClickListener;
import com.sk.sourcecircle.entity.MyCity;
import com.sk.sourcecircle.utils.CharacterParser;
import com.sk.sourcecircle.utils.DensityUtil;
import com.sk.sourcecircle.view.LetterListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/19.
 */

public class ChooseCityActivity extends BaseActivity implements LetterListView.OnTouchingLetterChangedListener, OnItemClickListener {

    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.hot_ll)
    RecyclerView hotLl;
    @BindView(R.id.data_ryc)
    ListView dataRyc;
    @BindView(R.id.letter_container)
    LetterListView letterContainer;
    @BindView(R.id.ed_search)
    EditText edSearch;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    private Map<String, Integer> letterIndex = new HashMap<>();

    private OverlayThread overlayThread; // 显示首字母对话框

    private String city;


    private TextView letterOverlay; // 对话框首字母textview
    private CityListAdapter cityListAdapter;
    private boolean isScroll;
    private boolean isOverlayReady;
    private Handler handler;
    private String areaJson;
    private List<MyCity> hotList = new ArrayList<>();
    List<MyCity> list = new ArrayList<MyCity>();
    ArrayList<MyCity> copy_list = new ArrayList<>();
    String[] citys = new String[]{"南昌", "武汉", "北京", "上海", "广州", "深圳", "成都", "重庆", "杭州", "青岛", "昆明", "长沙"};
    String[] cityIds = new String[]{"159", "204", "37", "109", "231", "233", "271", "270", "123", "171", "301", "217"};


    @Override
    protected int getContentView() {
        return R.layout.activity_choose_city;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initHotCity();

        characterParser = CharacterParser.getInstance();

        areaJson = getIntent().getStringExtra("data");
        city = getIntent().getStringExtra("city");

        if (city != null && city.length() > 0) {
            tvLocation.setText(city);
        } else {
            tvLocation.setText("定位失败");
        }

        list = JSONObject.parseArray(areaJson, MyCity.class);

        copy_list = (ArrayList<MyCity>) list;

        handler = new Handler();
        initOverlay();
        letterContainer.setOnTouchingLetterChangedListener(this);
        setupView();

        edSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable e) {

                String content = edSearch.getText().toString();
                if (content.length() > 0) {
                    ArrayList<MyCity> fileterList = (ArrayList<MyCity>) search(content);
                    cityListAdapter.updateListView(fileterList);
                    //mAdapter.updateData(mContacts);
                } else {
                    copy_list = (ArrayList<MyCity>) list;
                    cityListAdapter.updateListView(copy_list);
                }
                dataRyc.setSelection(0);
            }

        });
    }

    private void initHotCity() {
        for(int i = 0 ;i < citys.length ;i++){
            MyCity myCity = new MyCity();
            myCity.setCity_name(citys[i]);
            myCity.setCity_id(cityIds[i]);
            hotList.add(myCity);
        }
        hotLl.setLayoutManager(new GridLayoutManager(mContext,4));
        HotCityAdapter cityAdapter = new HotCityAdapter(R.layout.item_hot_city,hotList);
        hotLl.setAdapter(cityAdapter);
        cityAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("data", hotList.get(position));
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }


    /**
     * 取sort_key的首字母
     *
     * @param sortKey
     * @return
     */
    private String getSortLetterBySortKey(String sortKey) {
        if (sortKey == null || "".equals(sortKey.trim())) {
            return null;
        }
        String letter = "#";
        //汉字转换成拼音
        String sortString = sortKey.trim().substring(0, 1).toUpperCase(Locale.CHINESE);
        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {// 5.0以上需要判断汉字
            if (sortString.matches("^[\u4E00-\u9FFF]+$"))// 正则表达式，判断是否为汉字
                letter = getSortLetter(sortString.toUpperCase(Locale.CHINESE));
        }
        return letter;
    }


    /**
     * 名字转拼音,取首字母
     *
     * @param name
     * @return
     */
    private String getSortLetter(String name) {
        String letter = "#";
        if (name == null) {
            return letter;
        }
        //汉字转换成拼音
        String pinyin = characterParser.getSelling(name);
        String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);

        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        }
        return letter;
    }

    private void setupView() {
        letterContainer.setOnTouchingLetterChangedListener(this);
        cityListAdapter = new CityListAdapter(this, copy_list, letterIndex, this);
        dataRyc.setAdapter(cityListAdapter);
    }


    @OnClick(R.id.cancel)
    public void onViewClicked() {
        finish();
    }


    @Override
    public void onTouchingLetterChanged(String s) {
        isScroll = false;
        if (letterIndex.get(s) != null) {
            int position = letterIndex.get(s);
            dataRyc.setSelection(position);
            Pattern pattern = Pattern.compile("^[A-Za-z]+$");
            if (pattern.matcher(s).matches()) {
                letterOverlay.setTextSize(40);
            } else {
                letterOverlay.setTextSize(20);
            }
            letterOverlay.setText(s);
            letterOverlay.setVisibility(View.VISIBLE);
            handler.removeCallbacks(overlayThread);
            handler.postDelayed(overlayThread, 1000);
        }
    }


    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        overlayThread = new OverlayThread();
        isOverlayReady = true;
        LayoutInflater inflater = LayoutInflater.from(this);
        letterOverlay = (TextView) inflater.inflate(R.layout.v_letter_overlay, null);
        letterOverlay.setVisibility(View.INVISIBLE);

        int width = DensityUtil.dp2px(this, 65);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                width, width,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(letterOverlay, lp);
    }


    @Override
    public void clickItem(MyCity city) {
        Intent intent = new Intent();
        intent.putExtra("data", city);
        setResult(RESULT_OK, intent);
        finish();
    }

    private class OverlayThread implements Runnable {
        @Override
        public void run() {
            letterOverlay.setVisibility(View.GONE);
        }
    }


    /**
     * 模糊查询
     *
     * @param str
     * @return
     */
    private List<MyCity> search(String str) {
        List<MyCity> filterList = new ArrayList<MyCity>();// 过滤后的list

        for (MyCity contact : list) {
            if (contact.getCity_name() != null && contact.getPinyin() != null) {
                //姓名全匹配,姓名首字母简拼匹配,姓名全字母匹配
                boolean isNameContains = contact.getCity_name().toLowerCase(Locale.CHINESE)
                        .contains(str.toLowerCase(Locale.CHINESE));

                boolean isSortKeyContains = contact.getPinyin().toLowerCase(Locale.CHINESE)
                        .contains(str.toLowerCase(Locale.CHINESE));


                if (isNameContains || isSortKeyContains) {
                    if (!filterList.contains(contact)) {
                        filterList.add(contact);
                    }
                }
            }
        }
        Log.v("filterList", JSON.toJSONString(filterList));
        return filterList;
    }
}
